package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.dto.UserLoginDto;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.UserLoginVo;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 老人家属Service业务层处理
 * 
 * @author zzyl
 * @date 2025-10-22
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }


    @Autowired
    private WechatService wechatService;
    @Autowired
    private TokenService tokenService;

    private List<String> nickNameList = Arrays.asList("好似开花", "大吉大利", "今晚吃鸡", "三阳开泰");

    /**
     * 微信小程序登录接口
     *
     * @param userLoginDto
     * @return
     */
    @Override
    public UserLoginVo login(UserLoginDto userLoginDto) {

        // 1、获取微信唯一标识openId
        String openId = wechatService.getOpenId(userLoginDto.getCode());

        // 2、根据openId查询用户
        FamilyMember member = this.lambdaQuery().eq(FamilyMember::getOpenId, openId).one();

        // 3、如果用户不存在则新增用户（自动注册）
        if (member == null) {

            Collections.shuffle(nickNameList);
            // 生成随机昵称
            String nickName = nickNameList.get(0) + RandomStringUtils.randomNumeric(4);

            member = FamilyMember.builder()
                    .openId(openId)
                    .name(nickName)
                    .build();
            this.save(member);
        }

        // 4、如果手机号不存在则查询微信绑定的手机号
        if (StrUtil.isBlank(member.getPhone())) {
            String phoneNum = wechatService.getPhoneNum(userLoginDto.getPhoneCode());

            if (StrUtil.isNotBlank(phoneNum)) {
                // 5、新增或更新数据库中的手机号
                this.lambdaUpdate().eq(FamilyMember::getId, member.getId())
                        .set(FamilyMember::getPhone, phoneNum)
                        .update();
            }
        }

        // 6、基于openId和昵称生成token令牌
        String token = tokenService.createToken(Map.of(
                "userId", member.getId(),
                "nickName", member.getName()
        ));

        // 7、返回响应结果对象
        return UserLoginVo.builder()
                .token(token)
                .nickName(member.getName())
                .build();
    }
}
